package com.common.baselib.net;

import com.common.baselib.bean.ResultBean;
import com.common.baselib.ui.ToastUtil;
import com.common.baselib.utils.CommonUtils;
import com.common.baselib.utils.NetworkUtils;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

public class CallBackSubscriber<T> extends Subscriber<T> {

    //网络问题
    public final int NETWORK_ERROR = 101;
    //连接超时，也可能是网络问题
    public final int TIMEOUT_ERROR = 102;
    //服务器错误
    public final int SERVER_ERROR = 103;
    public SubscriberOnNextListener<T> mListener;

    public CallBackSubscriber(SubscriberOnNextListener<T> listener) {
        this.mListener = listener;
    }

    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {
        int errorCode = 0;
        if (!NetworkUtils.isAvailable(CommonUtils.getApp())) {
            ToastUtil.showToastShort(CommonUtils.getApp(), "网络中断，请检查您的网络状态");
            errorCode = NETWORK_ERROR;
        } else if (e instanceof SocketTimeoutException) {
            errorCode = SERVER_ERROR;
            ToastUtil.showToastShort(CommonUtils.getApp(), "数据返回失败，请稍后重试");
        } else if (e instanceof ConnectException) {
            errorCode = SERVER_ERROR;
            ToastUtil.showToastShort(CommonUtils.getApp(), "服务器异常，请稍后重试");
        }else if(e instanceof HttpException){
            errorCode = SERVER_ERROR;
            ToastUtil.showToastShort(CommonUtils.getApp(), "服务器异常，请稍后重试");
        }
        if (mListener != null) {
            mListener.onError(errorCode, "error");
        }
        e.printStackTrace();
    }

    @Override
    public void onNext(T t) {
        if (t == null) {
            return;
        }
        if (!NetworkUtils.isAvailable(CommonUtils.getApp())) {
            ToastUtil.showToastShort(CommonUtils.getApp(), "网络中断，请检查您的网络状态");
            if (mListener != null) {
                mListener.onError(NETWORK_ERROR, "网络中断，请检查您的网络状态");
            }
        }
        if (t instanceof ResultBean) {
            ResultBean resultBean = (ResultBean) t;
            if (resultBean.shouldReLogin()) {
                ToastUtil.showToastShort(CommonUtils.getApp(), resultBean.message);
                return;
            }
            if (resultBean.code == 200) {
                if (mListener != null) {
                    mListener.onNext(t);
                }
            } else {
                if (mListener != null) {
                    mListener.onError(resultBean.code, resultBean.message);
                }
            }
        }

    }
}
